﻿using HandyControl.Controls;
using Prism.DryIoc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MessageBox = HandyControl.Controls.MessageBox;

namespace PlaceOrder_Client.Updater
{
    public class ProgramUpdater
    {
        public static string CurrentVersion => Assembly.GetExecutingAssembly().GetName().Version.ToString();


        /// <summary>
        /// 传入 从数据库拿到最新版本号
        /// </summary>
        /// <param name="newVersion"></param>
        public static void CheckUpdate(string newVersion=null)
        {
            if (string.IsNullOrWhiteSpace(newVersion))
                return;
            if(newVersion==CurrentVersion)
            {
                Growl.InfoGlobal($"当前版本已是最新-{CurrentVersion}");
                return;
            }

            // 显示更新窗口
            //UpdaterView updateWindow = null;
            //PrismApplication.Current.Dispatcher.Invoke(() =>
            //{
            //    updateWindow = new UpdaterView();
            //    updateWindow.Show();
            //});
            // 下载并应用更新
            ApplyUpdate(newVersion);
            return;
        }
        private static void CreateBatchFile(string batchFilePath, string localPath, string tempPath)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(batchFilePath))
                {
                    writer.WriteLine("timeout /t 3 /nobreak > NUL"); // 等待 3 秒，确保应用程序完全退出
                    writer.WriteLine($"xcopy \"{tempPath}\\*.*\" \"{localPath}\" /E /H /C /Y");
                    writer.WriteLine($"start \"\" \"{Path.Combine(localPath, "YourApplication.exe")}\"");
                    writer.WriteLine("rd /s /q \"" + tempPath + "\""); // 删除临时目录
                }
            }
            catch (IOException ioex)
            {
                MessageBox.Show($"创建批处理文件时发生 IO 错误: {ioex.Message}");
            }
            catch (UnauthorizedAccessException uaex)
            {
                MessageBox.Show($"没有权限创建批处理文件: {uaex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建批处理文件时发生错误: {ex.Message}");
            }
        }

        private static void ApplyUpdate(string newVersion, UpdaterView updateWindow=null)
        {
            string serverPath = @"\\172.16.10.200\share\实盘客户端程序\"+newVersion; // 服务器共享文件夹路径
            string localPath = AppDomain.CurrentDomain.BaseDirectory; // 本地应用程序目录
            string tempPath = Path.Combine(Path.GetTempPath(), "UpdateTemp"); // 临时目录

            try
            {
                // 关闭应用程序的所有实例
                //CloseApplication();
                // 创建临时目录
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
                Directory.CreateDirectory(tempPath);

                // 从服务器下载文件到临时目录
                DownloadFiles(serverPath, tempPath);
                // 替换本地文件
                //ReplaceFiles(tempPath, localPath);
                // 创建批处理脚本
                string batchFilePath = Path.Combine(tempPath, "update.bat");
                CreateBatchFile(batchFilePath, localPath, tempPath);

                // 关闭更新窗口
                //PrismApplication.Current.Dispatcher.Invoke(() =>
                //{
                //    updateWindow.Close();
                //});

                //MessageBox.Show($"更新成功至版本 {newVersion}, 程序即将退出以应用更新");

                // 启动批处理脚本
                Process.Start(new ProcessStartInfo
                {
                    FileName = batchFilePath,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true
                });

                // 退出程序
                PrismApplication.Current.Shutdown();
            }
            catch (Exception ex)
            {
                //PrismApplication.Current.Dispatcher.Invoke(() =>
                //{
                //    updateWindow.Close();
                //});

                MessageBox.Show($"更新失败: {ex.Message}");
            }
        }


        private static void DownloadFiles(string serverPath, string localPath)
        {
            if (!Directory.Exists(serverPath))
            {
                throw new DirectoryNotFoundException($"服务器路径 {serverPath} 不存在。");
            }

            // 获取服务器文件列表
            string[] files = Directory.GetFiles(serverPath);

            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string destinationFile = Path.Combine(localPath, fileName);

                // 复制文件到本地路径
                File.Copy(file, destinationFile, true);
            }
        }
    }
}
